import pyaudio
import wave
import sys
import time
import os

# 尝试导入sounddevice作为备选录音方法
try:
    import sounddevice as sd
    import numpy as np
    HAVE_SOUNDDEVICE = True
except ImportError:
    HAVE_SOUNDDEVICE = False
    print("提示: 安装 sounddevice 和 numpy 可以获得备选录音方法: pip install sounddevice numpy")

def list_audio_devices():
    """
    列出所有可用的音频设备
    """
    p = pyaudio.PyAudio()
    print("=== PyAudio 设备列表 ===")
    
    default_input = None
    try:
        default_input = p.get_default_input_device_info()['index']
    except:
        pass
    
    for i in range(p.get_device_count()):
        try:
            info = p.get_device_info_by_index(i)
            if info['maxInputChannels'] > 0:  # 只显示有输入通道的设备
                marker = "> " if i == default_input else "  "
                print(f"{marker}{i:2d} {info['name']}, {info['hostApi']} ({info['maxInputChannels']} in, {info['maxOutputChannels']} out)")
        except:
            pass
    
    p.terminate()
    
    # 如果有sounddevice库，也显示它的设备列表
    if HAVE_SOUNDDEVICE:
        print("\n=== SoundDevice 设备列表 ===")
        try:
            devices = sd.query_devices()
            default_sd_input = sd.default.device[0]
            
            for i, device in enumerate(devices):
                if device['max_input_channels'] > 0:  # 只显示有输入通道的设备
                    marker = "> " if i == default_sd_input else "  "
                    print(f"{marker}{i:2d} {device['name']} ({device['max_input_channels']} in, {device['max_output_channels']} out)")
        except Exception as e:
            print(f"无法获取SoundDevice设备列表: {e}")
    
    return default_input

def record_audio_sounddevice(filename, duration=2, samplerate=16000, device_index=None):
    """
    使用SoundDevice录制音频 - 作为备选方法
    """
    if not HAVE_SOUNDDEVICE:
        print("❌ SoundDevice库未安装，无法使用此方法")
        print("请运行: pip install sounddevice numpy")
        return False
    
    print(f"使用SoundDevice录制音频...")
    
    # 设置录音参数
    channels = 1
    
    try:
        # 设置设备
        if device_index is not None:
            sd.default.device = device_index
            print(f"使用设备: {device_index}")
        
        # 获取设备信息
        try:
            device_info = sd.query_devices(device=sd.default.device[0])
            print(f"设备信息: {device_info['name']}")
            print(f"最大输入通道: {device_info['max_input_channels']}")
            print(f"默认采样率: {device_info['default_samplerate']}")
            
            # 确保设备支持输入
            if device_info['max_input_channels'] == 0:
                print(f"错误：设备 {device_index} 不支持音频输入")
                return False
        except Exception as e:
            print(f"无法获取设备信息: {e}")
            # 继续尝试录制
        
        # 开始录制
        print(f"开始录制... (设备 {sd.default.device[0]}, {duration}秒, {samplerate}Hz, 单声道)")
        
        # 计算总帧数
        total_samples = int(samplerate * duration * channels)
        
        # 创建一个空数组用于存储录音数据
        recording = np.zeros((total_samples, channels), dtype='int16')
        
        # 创建事件用于检测录音完成
        import threading
        event = threading.Event()
        
        # 回调函数，用于非阻塞录音
        def callback(indata, frames, time, status):
            if status:
                print(f"录音回调状态: {status}")
            recording_slice = recording[frames_recorded[0]:frames_recorded[0] + frames]
            if len(recording_slice) < len(indata):
                recording_slice = recording[frames_recorded[0]:]
                recording_slice[:] = indata[:len(recording_slice)]
            else:
                recording_slice[:] = indata
            frames_recorded[0] += frames
            if frames_recorded[0] >= total_samples:
                event.set()
        
        # 使用非阻塞模式录制
        frames_recorded = [0]  # 使用列表以便在回调中修改
        
        # 使用信号模块添加强制超时
        import signal
        
        def timeout_handler(signum, frame):
            raise TimeoutError("录音超时，强制结束")
        
        # 创建输入流
        print("创建音频输入流...")
        try:
            stream = sd.InputStream(
                samplerate=samplerate,
                channels=channels,
                dtype='int16',
                callback=callback,
                blocksize=1024,
                device=device_index
            )
        except Exception as e:
            print(f"创建音频流失败: {e}")
            print("尝试使用默认参数...")
            try:
                stream = sd.InputStream(
                    callback=callback,
                    blocksize=1024
                )
            except Exception as e:
                print(f"创建音频流再次失败: {e}")
                return False
        
        # 设置超时
        timeout = duration + 5  # 额外5秒超时
        max_timeout = duration + 10  # 绝对最大超时
        
        # 设置信号超时
        signal.signal(signal.SIGALRM, timeout_handler)
        signal.alarm(max_timeout)  # 设置绝对超时
        
        # 启动流
        print("启动录音流...")
        try:
            with stream:
                # 显示进度
                start_time = time.time()
                
                # 使用超时等待录音完成
                try:
                    while not event.is_set() and time.time() - start_time < timeout:
                        time.sleep(0.1)  # 更频繁地更新进度
                        elapsed = time.time() - start_time
                        if elapsed > duration:
                            progress = 100.0
                        else:
                            progress = (elapsed / duration) * 100
                        
                        frames_status = f"{frames_recorded[0]}/{total_samples}"
                        print(f"\r录制进度: {progress:.1f}% ({frames_status}帧)", end="", flush=True)
                        
                        # 如果已经超过了预期时间很多，强制结束
                        if elapsed > timeout - 1:
                            print("\n录音超时，强制结束")
                            break
                        
                        # 如果已经录制了足够的帧数，提前结束
                        if frames_recorded[0] >= total_samples * 0.9:  # 90%就足够了
                            print("\n已录制足够的数据，提前结束")
                            break
                except KeyboardInterrupt:
                    print("\n录音被用户中断")
                except TimeoutError:
                    print("\n录音超时，强制结束")
                finally:
                    # 取消信号超时
                    signal.alarm(0)
        except Exception as e:
            print(f"录音流操作失败: {e}")
            signal.alarm(0)  # 取消超时
            return False
        
        # 检查是否完成录音
        if frames_recorded[0] < total_samples:
            print(f"\n⚠️ 警告: 录音未完全完成，只录制了 {frames_recorded[0]}/{total_samples} 帧")
        else:
            print("\n✅ 录音完成!")
        
        # 保存为WAV文件
        try:
            print(f"正在保存音频文件: {filename}...")
            
            # 确保目录存在
            dir_name = os.path.dirname(filename)
            if dir_name and not os.path.exists(dir_name):
                os.makedirs(dir_name)
            
            # 确保数据有效
            if frames_recorded[0] == 0:
                print("⚠️ 警告: 没有录制到任何数据")
                # 创建一个静音文件
                recording = np.zeros((samplerate * 1, channels), dtype='int16')  # 1秒静音
            elif frames_recorded[0] < total_samples:
                # 裁剪数组到实际录制的长度
                recording = recording[:frames_recorded[0]]
                
            try:
                # 尝试使用scipy保存
                try:
                    import scipy.io.wavfile as wavfile
                    wavfile.write(filename, samplerate, recording)
                except ImportError:
                    # 如果没有scipy，使用wave模块
                    with wave.open(filename, 'wb') as wf:
                        wf.setnchannels(channels)
                        wf.setsampwidth(2)  # 16位 = 2字节
                        wf.setframerate(samplerate)
                        wf.writeframes(recording.tobytes())
                
                print("音频数据写入成功")
            except Exception as e:
                print(f"写入音频数据时出错: {e}")
                return False
            
            # 验证文件是否成功创建
            if os.path.exists(filename):
                file_size = os.path.getsize(filename)
                print(f"音频已保存为: {filename}")
                print(f"文件大小: {file_size} 字节")
                
                if file_size > 1000:  # 如果文件大于1KB，说明录制成功
                    print("✅ 录制成功!")
                    return True
                else:
                    print("⚠️ 警告: 文件太小，可能录制失败")
                    return False
            else:
                print(f"❌ 错误: 文件 {filename} 未能创建")
                return False
                
        except Exception as e:
            print(f"保存文件时出错: {e}")
            print("如果缺少scipy，请安装: pip install scipy")
            return False
            
    except Exception as e:
        print(f"录制音频时出错: {e}")
        return False
    
    return True

def record_audio_pyaudio(filename, duration=2, samplerate=16000, device_index=None):
    """
    使用PyAudio录制音频 - 改进版本，处理Jetson设备
    """
    # 音频参数 - 优化为VAD兼容
    chunk = 1024  # 每次读取的帧数
    format = pyaudio.paInt16  # 16位深度
    channels = 1  # 单声道 - 关键！
    
    # 导入信号模块，用于超时控制
    import signal
    
    p = pyaudio.PyAudio()
    
    # 如果没有指定设备，使用默认输入设备
    if device_index is None:
        try:
            device_index = p.get_default_input_device_info()['index']
            print(f"使用默认输入设备: {device_index}")
        except:
            print("无法获取默认输入设备，使用设备4")
            device_index = 4
    
    # 获取设备信息
    try:
        device_info = p.get_device_info_by_index(device_index)
        print(f"设备信息: {device_info['name']}")
        print(f"最大输入通道: {device_info['maxInputChannels']}")
        print(f"默认采样率: {device_info['defaultSampleRate']}")
        
        # 确保设备支持输入
        if device_info['maxInputChannels'] == 0:
            print(f"错误：设备 {device_index} 不支持音频输入")
            p.terminate()
            return False
            
    except Exception as e:
        print(f"无法获取设备 {device_index} 的信息: {e}")
        p.terminate()
        return False
    
    print(f"开始录制... (设备 {device_index}, {duration}秒, {samplerate}Hz, 单声道)")
    
    stream = None
    try:
        # 添加超时设置
        import signal
        
        def timeout_handler(signum, frame):
            raise TimeoutError("打开音频流超时")
        
        # 设置5秒超时
        signal.signal(signal.SIGALRM, timeout_handler)
        signal.alarm(5)
        
        print("正在初始化音频设备...")
        
        # 打开音频流 - 添加更多参数以确保兼容性
        stream = p.open(
            format=format,
            channels=channels,
            rate=samplerate,
            input=True,
            input_device_index=device_index,  # 明确指定输入设备
            frames_per_buffer=chunk,
            start=False  # 先不开始，手动启动
        )
        
        # 取消超时
        signal.alarm(0)
        
        # 手动启动流
        print("正在启动音频流...")
        stream.start_stream()
        print("音频流启动成功!")
        
        frames = []
        
        # 录制音频 - 添加进度显示和超时保护
        total_frames = int(samplerate / chunk * duration)
        frames = []
        
        # 设置读取数据的超时
        signal.signal(signal.SIGALRM, timeout_handler)
        
        print(f"开始录制，预计采集 {total_frames} 帧数据...")
        
        # 设置整体录制超时（比预期时间长5秒）
        overall_timeout = duration + 5
        start_time = time.time()
        
        for i in range(total_frames):
            try:
                # 检查总体超时
                if time.time() - start_time > overall_timeout:
                    print("\n录制总时间超时，强制结束")
                    break
                    
                # 为每次读取设置2秒超时
                signal.alarm(2)
                
                # 尝试读取数据
                data = stream.read(chunk, exception_on_overflow=False)
                frames.append(data)
                
                # 取消超时
                signal.alarm(0)
                
                # 显示进度
                if i % 10 == 0 or i == total_frames - 1:
                    progress = (i / total_frames) * 100
                    print(f"\r录制进度: {progress:.1f}% ({i}/{total_frames}帧)", end="", flush=True)
                    
            except TimeoutError:
                print("\n读取音频数据超时，尝试继续...")
                continue
            except Exception as e:
                print(f"\n读取音频数据时出错: {e}")
                break
        
        # 确保至少有一些数据
        if len(frames) == 0:
            print("\n⚠️ 警告: 没有采集到任何音频数据!")
            # 生成一个空白帧以便保存文件
            frames = [b'\x00' * chunk * 2]  # 16位深度 = 2字节/样本
                
        # 确保取消所有超时
        signal.alarm(0)
        
        print(f"\n录制完成! 采集了 {len(frames)} 帧数据")
        
    except Exception as e:
        print(f"打开音频流时出错: {e}")
        p.terminate()
        return False
    
    finally:
        # 确保资源清理
        if stream:
            try:
                stream.stop_stream()
                stream.close()
            except:
                pass
        p.terminate()
    
    # 保存为WAV文件
    try:
        print(f"正在保存音频文件: {filename}...")
        
        # 确保目录存在
        import os
        dir_name = os.path.dirname(filename)
        if dir_name and not os.path.exists(dir_name):
            os.makedirs(dir_name)
        
        # 确保frames不为空
        if not frames:
            print("⚠️ 警告: 没有音频数据可保存")
            frames = [b'\x00' * chunk * 2 * 16000]  # 生成1秒的静音
        
        # 保存文件
        with wave.open(filename, 'wb') as wf:
            wf.setnchannels(channels)
            wf.setsampwidth(p.get_sample_size(format))
            wf.setframerate(samplerate)
            try:
                wf.writeframes(b''.join(frames))
                print(f"音频数据写入成功")
            except Exception as e:
                print(f"写入音频数据时出错: {e}")
                return False
        
        # 验证文件是否成功创建
        if os.path.exists(filename):
            file_size = os.path.getsize(filename)
            print(f"音频已保存为: {filename}")
            print(f"文件大小: {file_size} 字节")
            
            if file_size > 1000:  # 如果文件大于1KB，说明录制成功
                print("✅ 录制成功!")
                return True
            else:
                print("⚠️ 警告: 文件太小，可能录制失败")
                return False
        else:
            print(f"❌ 错误: 文件 {filename} 未能创建")
            return False
            
    except Exception as e:
        print(f"保存文件时出错: {e}")
        return False

def record_audio(filename, duration=2, samplerate=16000, device_index=None, use_sounddevice=False, use_simple=False):
    """
    录制音频的统一接口 - 自动选择最佳方法
    """
    # 如果指定使用系统命令
    if use_simple:
        print("使用系统命令录制...")
        return record_audio_simple(filename, duration, samplerate)
        
    # 如果指定使用SoundDevice且可用
    if use_sounddevice and HAVE_SOUNDDEVICE:
        print("使用SoundDevice录制...")
        return record_audio_sounddevice(filename, duration, samplerate, device_index)
    
    # 否则使用PyAudio
    print("使用PyAudio录制...")
    return record_audio_pyaudio(filename, duration, samplerate, device_index)

def test_device_recording(device_index, duration=1, use_sounddevice=False, use_simple=False):
    """
    测试特定设备的录制功能
    """
    print(f"\n🧪 测试设备 {device_index}...")
    
    filename = f"test_device_{device_index}.wav"
    success = record_audio(filename, duration=duration, device_index=device_index, 
                          use_sounddevice=use_sounddevice, use_simple=use_simple)
    
    if success:
        print(f"✅ 设备 {device_index} 录制成功!")
        # 播放测试
        try:
            import os
            os.system(f"aplay {filename} 2>/dev/null")
        except:
            pass
    else:
        print(f"❌ 设备 {device_index} 录制失败")
    
    return success

def validate_device(device_id):
    """
    检查设备是否可用于录音
    """
    print(f"🔍 检查设备 {device_id} 是否可用...")
    
    p = pyaudio.PyAudio()
    
    try:
        # 设置超时
        import signal
        
        def timeout_handler(signum, frame):
            raise TimeoutError("设备检查超时")
        
        signal.signal(signal.SIGALRM, timeout_handler)
        signal.alarm(3)  # 3秒超时
        
        # 获取设备信息
        try:
            device_info = p.get_device_info_by_index(device_id)
            signal.alarm(0)  # 取消超时
            
            if device_info['maxInputChannels'] == 0:
                print(f"❌ 设备 {device_id} 不支持输入")
                return False
                
            # 确认设备可以打开
            print(f"尝试打开设备 {device_id} 进行测试...")
            signal.alarm(3)  # 重新设置超时
            
            stream = p.open(
                format=pyaudio.paInt16,
                channels=1,
                rate=16000,
                input=True,
                input_device_index=device_id,
                frames_per_buffer=1024,
                start=False
            )
            
            signal.alarm(0)  # 取消超时
            
            # 尝试启动流
            print("尝试启动音频流...")
            signal.alarm(3)
            stream.start_stream()
            signal.alarm(0)
            
            # 关闭流
            stream.stop_stream()
            stream.close()
            
            print(f"✅ 设备 {device_id} 可用")
            return True
            
        except Exception as e:
            print(f"❌ 设备 {device_id} 不可用: {e}")
            return False
            
    except TimeoutError:
        print(f"❌ 设备 {device_id} 操作超时")
        return False
    finally:
        signal.alarm(0)  # 确保取消超时
        p.terminate()
        
    return False

def find_working_device():
    """
    自动找到能工作的录制设备
    """
    print("🔍 自动搜索可用的录制设备...")
    
    # 导入信号模块，设置全局超时
    import signal
    
    def global_timeout_handler(signum, frame):
        raise TimeoutError("设备搜索超时")
    
    # 测试设备4-23（Jetson APE设备）
    working_devices = []
    
    # 设置全局超时时间为30秒
    signal.signal(signal.SIGALRM, global_timeout_handler)
    signal.alarm(30)
    
    try:
        for device_id in [4, 5, 6, 7, 8]:  # 先测试前几个设备
            try:
                # 每个设备测试最多允许10秒
                print(f"测试设备 {device_id}...")
                if test_device_recording(device_id, duration=1):
                    working_devices.append(device_id)
                    print(f"设备 {device_id} 工作正常！")
                    break  # 找到第一个能工作的就停止
            except KeyboardInterrupt:
                print("\n测试被用户中断")
                break
            except TimeoutError:
                print(f"设备 {device_id} 测试超时，跳过")
                continue
            except Exception as e:
                print(f"测试设备 {device_id} 时出错: {e}")
    finally:
        # 取消超时
        signal.alarm(0)
    
    # 如果PyAudio方法失败，尝试SoundDevice
    if not working_devices and HAVE_SOUNDDEVICE:
        print("\n尝试使用SoundDevice方法...")
        try:
            # 获取默认设备
            default_device = sd.default.device[0]
            print(f"测试SoundDevice默认设备 {default_device}...")
            
            if test_device_recording(default_device, duration=1, use_sounddevice=True):
                working_devices.append(f"sd:{default_device}")  # 添加前缀以区分
                print(f"SoundDevice设备 {default_device} 工作正常！")
        except Exception as e:
            print(f"测试SoundDevice设备时出错: {e}")
    
    return working_devices

# 安装所需库: pip install pyaudio

def record_audio_simple(filename, duration=2, samplerate=16000, device="default"):
    """
    最简单的录音方法 - 使用系统命令
    """
    print(f"尝试使用系统命令录音...")
    
    try:
        # 检查是否有arecord命令
        import subprocess
        try:
            subprocess.run(["which", "arecord"], check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        except:
            print("系统中没有找到arecord命令")
            return False
        
        # 确保目录存在
        dir_name = os.path.dirname(filename)
        if dir_name and not os.path.exists(dir_name):
            os.makedirs(dir_name)
        
        # 使用arecord录制
        print(f"使用arecord录制 {duration} 秒音频...")
        
        # 构建命令 - 使用列表形式更安全
        cmd = [
            "arecord",
            "-D", device,              # 设备
            "-d", str(duration),       # 持续时间
            "-f", "S16_LE",            # 16位有符号小端格式
            "-c", "1",                 # 单声道
            "-r", str(samplerate),     # 采样率
            "-t", "wav",               # WAV格式
            "--quiet",                 # 安静模式，减少输出
            filename                   # 输出文件
        ]
        
        cmd_str = " ".join(cmd)
        print(f"执行命令: {cmd_str}")
        
        # 设置超时，比指定时间长5秒
        timeout = duration + 5
        
        # 执行命令 - 使用非阻塞方式并显示进度
        try:
            process = subprocess.Popen(
                cmd,
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE,
                text=True
            )
        except Exception as e:
            print(f"启动录音命令失败: {e}")
            return False
        
        # 显示进度
        start_time = time.time()
        try:
            while process.poll() is None:
                # 检查是否超时
                elapsed = time.time() - start_time
                if elapsed > timeout:
                    print("\n录音命令超时，强制终止")
                    process.terminate()
                    time.sleep(0.5)
                    process.kill()  # 确保进程被终止
                    break
                    
                # 显示进度
                if elapsed > duration:
                    progress = 100.0
                else:
                    progress = (elapsed / duration) * 100
                    
                print(f"\r录制进度: {progress:.1f}% ({elapsed:.1f}/{duration}秒)", end="", flush=True)
                time.sleep(0.1)
            
            # 如果进程仍在运行，强制终止
            if process.poll() is None:
                process.terminate()
                time.sleep(0.5)
                if process.poll() is None:
                    process.kill()
        except KeyboardInterrupt:
            print("\n录音被用户中断")
            process.terminate()
            time.sleep(0.5)
            process.kill()
            
        # 获取返回码和输出
        try:
            returncode = process.wait(timeout=2)
            stdout, stderr = process.communicate(timeout=2)
        except subprocess.TimeoutExpired:
            print("\n获取进程输出超时，强制终止")
            process.kill()
            returncode = -1
            stdout, stderr = "", "进程无响应"
        
        # 无论返回码如何，都检查文件是否存在并有效
        if os.path.exists(filename):
            file_size = os.path.getsize(filename)
            print(f"\n音频已保存为: {filename}")
            print(f"文件大小: {file_size} 字节")
            
            if file_size > 1000:  # 如果文件大于1KB，说明录制成功
                print("✅ 录制成功!")
                return True
            else:
                print("⚠️ 警告: 文件太小，可能录制失败")
        else:
            print(f"\n❌ 错误: 文件 {filename} 未能创建")
        
        # 如果文件无效，则显示错误信息
        if returncode != 0:
            print(f"录制过程返回码: {returncode}")
            if stderr:
                print(f"错误信息: {stderr}")
        
        # 尝试使用备选命令
        print("\n尝试使用备选命令录制...")
        try:
            # 使用更简单的命令
            simple_cmd = f"arecord -d {duration} -D {device} -t wav {filename}"
            print(f"执行命令: {simple_cmd}")
            
            # 直接执行命令，阻塞模式
            result = subprocess.run(simple_cmd, shell=True, timeout=duration+5)
            
            # 检查结果
            if os.path.exists(filename) and os.path.getsize(filename) > 1000:
                print("✅ 备选命令录制成功!")
                return True
        except Exception as e:
            print(f"备选命令也失败了: {e}")
        
        return False
            
    except subprocess.TimeoutExpired:
        print("\n录音命令超时")
        return False
    except KeyboardInterrupt:
        print("\n录音被用户中断")
        return False
    except Exception as e:
        print(f"\n执行录音命令时出错: {e}")
        return False

def main():
    """
    主函数 - 提供多种使用方式
    """
    if len(sys.argv) > 1:
        command = sys.argv[1]
        
        if command == "list":
            # 列出设备
            default_device = list_audio_devices()
            print(f"\n默认输入设备索引: {default_device}")
            
        elif command == "test":
            # 测试特定设备
            if len(sys.argv) > 2:
                device_id = int(sys.argv[2])
                use_sd = False
                if len(sys.argv) > 3 and sys.argv[3].lower() == "sd":
                    use_sd = True
                    print("使用SoundDevice进行测试")
                test_device_recording(device_id, duration=3, use_sounddevice=use_sd)
            else:
                print("用法: python3 record_wav.py test <设备索引> [sd]")
                
        elif command == "check":
            # 检查设备是否可用
            if len(sys.argv) > 2:
                device_id = int(sys.argv[2])
                validate_device(device_id)
            else:
                print("用法: python3 record_wav.py check <设备索引>")
                
        elif command == "find":
            # 自动找到可用设备
            working_devices = find_working_device()
            if working_devices:
                print(f"\n✅ 找到可用设备: {working_devices}")
                print(f"推荐使用设备 {working_devices[0]}")
            else:
                print("\n❌ 未找到可用的录制设备")
                
        elif command == "simple":
            # 使用arecord简单录制
            duration = 3
            device = "default"
            
            if len(sys.argv) > 2:
                try:
                    duration = int(sys.argv[2])
                except:
                    print("录制时长必须是数字(秒)")
                    return
            
            if len(sys.argv) > 3:
                device = sys.argv[3]
            
            filename = f"recording_simple_{int(time.time())}.wav"
            print(f"使用系统命令录制 {duration} 秒音频到 {filename}")
            
            success = record_audio_simple(filename, duration, 16000, device)
            
            if success:
                print(f"\n🎉 录制成功! 文件: {filename}")
                print(f"现在可以用于VAD测试:")
                print(f"python3 vad_detect.py --test-file {filename}")
            else:
                print(f"\n💡 尝试其他方法录制")
                
        elif command == "record":
            # 录制音频
            device_id = 4  # 默认使用设备4
            duration = 3   # 默认3秒
            use_sd = False # 默认使用PyAudio
            use_simple = False # 默认不使用系统命令
            
            if len(sys.argv) > 2:
                # 检查录音方式
                if sys.argv[2].lower() == "sd":
                    use_sd = True
                    print("使用SoundDevice录制")
                    if len(sys.argv) > 3:
                        try:
                            device_id = int(sys.argv[3])
                        except:
                            device_id = None  # 使用默认设备
                    else:
                        device_id = None  # 使用默认设备
                elif sys.argv[2].lower() == "simple":
                    use_simple = True
                    print("使用系统命令录制")
                    device_id = "default"  # 默认设备
                    if len(sys.argv) > 3:
                        device_id = sys.argv[3]  # 设备参数
                else:
                    # 使用PyAudio
                    try:
                        device_id = int(sys.argv[2])
                    except:
                        print("设备ID必须是数字")
                        return
            
            if len(sys.argv) > 3 and not use_sd and not use_simple:
                try:
                    duration = int(sys.argv[3])
                except:
                    print("录制时长必须是数字(秒)")
                    return
            
            # 如果使用系统命令
            if use_simple:
                filename = f"recording_simple_{int(time.time())}.wav"
                success = record_audio_simple(filename, duration, 16000, device_id)
            else:
                # 如果使用PyAudio，先验证设备是否可用
                if not use_sd:
                    if not validate_device(device_id):
                        print(f"\n⚠️ 设备 {device_id} 可能不可用，建议尝试其他设备")
                        print(f"提示: 运行 'python3 record_wav.py find' 查找可用设备")
                        print(f"或者尝试: 'python3 record_wav.py record sd' 使用SoundDevice")
                        print(f"或者尝试: 'python3 record_wav.py record simple' 使用系统命令")
                        
                        # 询问用户是否继续
                        answer = input("是否仍然尝试录制? (y/n): ").strip().lower()
                        if answer != 'y' and answer != 'yes':
                            return
                
                filename = f"recording_device_{device_id}.wav"
                success = record_audio(filename, duration=duration, device_index=device_id, use_sounddevice=use_sd)
            
            if success:
                print(f"\n🎉 录制成功! 文件: {filename}")
                print(f"现在可以用于VAD测试:")
                print(f"python3 vad_detect.py --test-file {filename}")
            else:
                print(f"\n💡 尝试其他录音方法:")
                print(f"  python3 record_wav.py record sd    # 使用SoundDevice")
                print(f"  python3 record_wav.py record simple # 使用系统命令")
                print(f"  python3 record_wav.py find         # 自动查找可用设备")
        else:
            print("未知命令")
            show_usage()
    else:
        show_usage()

def show_usage():
    """
    显示使用说明
    """
    print("🎤 Jetson 音频录制工具")
    print("=" * 30)
    print("用法:")
    print("  python3 record_wav.py list              # 列出音频设备")
    print("  python3 record_wav.py test <设备ID> [sd] # 测试特定设备")
    print("  python3 record_wav.py check <设备ID>     # 快速检查设备是否可用")
    print("  python3 record_wav.py find              # 自动找到可用设备")
    print("  python3 record_wav.py record [设备ID] [时长] # 录制音频 (PyAudio)")
    print("  python3 record_wav.py record sd [设备ID]    # 录制音频 (SoundDevice)")
    print("  python3 record_wav.py record simple [设备]  # 录制音频 (系统命令)")
    print("  python3 record_wav.py simple [时长] [设备]   # 直接使用系统命令录制")
    print("\n示例:")
    print("  python3 record_wav.py list")
    print("  python3 record_wav.py test 4")
    print("  python3 record_wav.py test 0 sd")
    print("  python3 record_wav.py check 4")
    print("  python3 record_wav.py record 4 5")
    print("  python3 record_wav.py record sd")
    print("  python3 record_wav.py record simple hw:1,0")
    print("  python3 record_wav.py simple 5 hw:1,0")

if __name__ == "__main__":
    main()